from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

from wepapi.models import PrettyNum, user
from wepapi.utils.bootstrap import BootStrapModelForm
from django import forms


class UserFrom(BootStrapModelForm):
    class Meta:
        model = user
        fields = ["name", "pwd", "age", "account", "create_time", "gender", "depart"]

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     for name, field in self.fields.items():
    #         field.widget.attrs = {
    #             'class': 'form-control',
    #             'placeholder': '请输入' + field.label,
    #         }

class PrettyNumForm(BootStrapModelForm):
    # # 对提交的字段验证方式1：
    mobile = forms.CharField(
        # 字段
        label="手机号码",
        # 正则表达式（1开头，再只能3-9里面选择，后面只能9个数，报错）
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    # price = forms.CharField(min_length=1, label="价格")
    # level = forms.CharField( label="级别")
    # status = forms.CharField( label="状态")

    class Meta:
        model = PrettyNum
        # 获取字段
        fields = "__all__"  # 所有字段
        # fields = ["mobile", "price", "level", "status"]
        # exclude = ["price"]       # 排除字段其余的都显示

    #
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     for name, field in self.fields.items():
    #         field.widget.attrs = {
    #             'class': 'form-control',
    #             'placeholder': '请输入' + field.label,
    #         }

    def clean_mobile(self):
        mobile = self.cleaned_data.get('mobile')
        if len(mobile) != 11:
            # 验证不通过
            raise ValidationError('格式错误')
        if PrettyNum.objects.filter(mobile=mobile).exists():
            raise forms.ValidationError("该手机号码已存在。")
        return mobile

    # 对提交的字段验证方式2：
    # def clean_mobile(self):
    #     txt_moble = self.cleaned_data["mobile"]
    #     if len(txt_moble) != 11:
    #         # 验证不通过
    #         raise ValidationError('格式错误')
    #     # 验证通过
    #     return txt_moble
class PrettyEditNumForm(BootStrapModelForm):
    """
    mobile = forms.CharField(disabled=True, label="手机号码")
    disabled=True 不可编辑
    """
    mobile = forms.CharField(disabled=True, label="手机号码")

    class Meta:
        model = PrettyNum
        fields = ["mobile", "price", "level", "status"]

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     for name, field in self.fields.items():
    #         field.widget.attrs = {
    #             'class': 'form-control',
    #             'placeholder': '请输入' + field.label,
    #         }

    def clean_mobile(self):
        mobile = self.cleaned_data.get('mobile')
        if len(mobile) != 11:
            # 验证不通过
            raise ValidationError('格式错误')
        if PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=mobile).exists():
            raise forms.ValidationError("该手机号码已存在。")
        return mobile
